<?php
// ==========================================================
// | IntegralOrder
// ==========================================================
// | Time：2021/12/18 21:16
// ==========================================================
// | Author: 陈 <1035812848@qq.com>
// ==========================================================

namespace app\common\model;

use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

class IntegralOrder extends Model
{
    // 表名
    protected $name = 'integral_order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime   = 'createtime';
    protected $updateTime   = 'updatetime';

    /**
     * Name: 下单
     * Date: 2021/12/18 21:18
     * @param array $params
     * @return bool
     */
    public function add($params = [])
    {
        if ($params) {
            $result = false;

            $goods  = IntegralGoods::get($params['integral_goods_id']);
            $user   = User::get($params['user_id']);

            if (!$user) {
                $this->error = __('用户不存在');
                return false;
            }

            if (!$goods) {
                $this->error = __('商品不存在');
                return false;
            }

            if ($goods->inventory <= 0) {
                $this->error = __('商品库存不足');
                return false;
            }

            $extend = [
                'order_no'  => date('Ymds') . mt_rand(10000, 99999) . Random::numeric(4),
                'title'     => $goods->title,
            ];

            $params = array_merge($params, $extend);

            if ($user->score < $params['number'] * $goods->integral) {
                $this->error = __('积分不足');
                return false;
            }

            Db::startTrans();
            try {
                $goods->sales_count += $params['number'];
                $goods->inventory   -= $params['number'];
                if (!$goods->save()) {
                    Db::rollback();
                    $this->error = __('更新失败');
                    return false;
                }
                $validate   = "app\\common\\validate\\IntegralOrder.add";
                $result     = $this->validateFailException(true)->validate($validate)->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            } catch (PDOException $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            } catch (\Exception $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            }

            if ($result !== false) {
                User::score(-$params['number'] * $goods->integral, $user->id, '积分兑换商品');
                return true;
            } else {
                $this->error = __('No rows were inserted');
                return false;
            }
        }

        $this->error = __('Parameter %s can not be empty', '');
        return false;
    }
}